#include <stdio.h>
#include <stdlib.h>
#include "lwip/apps/httpd.h"
#include "lwip/apps/httpd_opts.h"
#include "lwip/def.h"
#include "lwip/apps/fs.h"
#include <string.h>
#include "httpd_cgi.h"

#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

static httpd_cgi_param *g_httpd_cgi_param_head;

__attribute__((weak)) const char *httpd_setting_update(int iIndex, int iNumParams, char *pcParam[], char *pcValue[])
{
    for (int i = 0; i < iNumParams; i++) {
        httpd_cgi_param *head = g_httpd_cgi_param_head;
    
        while (head) {
            if (strcmp(head->param, pcParam[i]) == 0) {
                head->set_cb(pcValue[i]);
                break;
            }
            head = head->next;
        }
    }

    return "/succ.html";
}

static tCGI g_CGIs[] = {
    { "/setting.cgi", httpd_setting_update },
};
 
void httpd_cgi_init(void)
{
    http_set_cgi_handlers(g_CGIs, ARRAY_SIZE(g_CGIs));
}
void httpd_cgi_add_param(httpd_cgi_param *client, const char *param, void (*set_cb)(char *value))
{
    client->param = param;
    client->set_cb = set_cb;
    client->next = g_httpd_cgi_param_head;
    g_httpd_cgi_param_head = client;
}
